//
//  selectMemberViewController.m
//  SouthChina
//  添加群成员选择用户主界面
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "selectMemberViewController.h"
#import "ContactDao.h"
#import "selectTableViewController.h"
#import "selectGroupViewController.h"
#import "CreateGroupViewController.h"
#import "GroupInfoViewController.h"
#import "SearchGrpMemberViewController.h"
#import "ShowStudentViewController.h"
#import "selectMemberTableViewCell.h"

@interface selectMemberViewController ()<UITableViewDataSource,UITableViewDelegate,SYTabBarDelegate,UnitViewDelegate,UISearchBarDelegate>
{
    NSMutableArray * orgArr;
    NSMutableArray *alldata;//存对应的数据
    NSArray * titleskey; //标题关键字列表
    NSArray * titles; //标题列表
    NSArray * titlePic;//图像
    NSMutableArray *selectedArr;//列表是否展开状态
    NSMutableArray *groupdata;//群组数据
    NSMutableArray *chatdata;//讨论组数据
    NSMutableArray *recentlydata;//最近联系人数据
    int nGroupCnt;// 群个数包括群组和讨论组
}

@end

@implementation selectMemberViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addTitleBarWithBackBtn:@"添加群成员" needReturn:TRUE];
    UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"selectMemberViewBody" owner:self options:nil] objectAtIndex:0];
    
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:viewBody];
    
    nGroupCnt = 0;
    alldata = [[NSMutableArray alloc] init];
    selectedArr = [[NSMutableArray alloc] init];
    groupdata = [[NSMutableArray alloc] init];
    chatdata = [[NSMutableArray alloc] init];
    recentlydata = [[NSMutableArray alloc] init];
    [selectedArr removeAllObjects];
    
    _selectMemberList.isDoneButton = YES;
    _selectMemberList = [_selectMemberList initWithFrame:_selectMemberList.frame];
    _selectMemberList.delegate = self;
    
    _tabContacts.delegate = self;
    _tabContacts.dataSource = self;
    _tabContacts.bounces = NO;
    
    _searchMember.showsCancelButton=NO;
    _searchMember.barStyle=UIBarStyleDefault;
    _searchMember.placeholder = @"输入用户名或群组名搜索";
    _searchMember.delegate = self;
    _searchMember.keyboardType = UIKeyboardTypeDefault;
    
    titles = @[@"我的群组",@"我的讨论组",@"最近联系人",@"我的好友",@"我的同学",@"我的同事",@"我的舍友",@"我的老师",@"我的辅导员",@"我授科的学生",@"我辅导的学生"];
    titleskey =@[@"Group",@"Chat",@"RecentlyContact",@"Friend",@"Classmate",@"Workmate",@"Roommate",@"Teacher",@"Instructor",@"ClassStudent",@"InstruStudent"];
    titlePic = @[@"icon_groups.png",@"icon_chats.png",@"recently_contact.png",@"myfriend.png",@"myclassmate.png",@"myworkmate.png",@"myroommate.png",@"myteacher.png",@"myinstructor.png",@"mystudent.png",@"mystudent.png"];
    
    
    
    [self refreshTableView];
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //单独跳转到一个搜索页面
    SearchGrpMemberViewController * searchgroup =[[SearchGrpMemberViewController alloc] initWithNibName:nil bundle:nil];
    searchgroup.selectedContact = _selectedContact;
    searchgroup.CreateType = _CreateType;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:searchgroup animated:YES];
    return  NO;//返回NO不显示键盘
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_selectMemberList removeAll];
    
    for( Contact * contact in _selectedContact)
    {
        [_selectMemberList addNewUnit:contact];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

}

-(void) refreshTableView{
    //先清空再加载
    [alldata removeAllObjects];
    groupdata  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Group' and operate='U' "]];
    chatdata  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:@"where org_type='Chat' and operate='U' "]];
    recentlydata  = [[NSMutableArray alloc] initWithArray:[ContactDao queryRecentlyCcontact:@""]];
    
    //我的群组
    if(groupdata.count>0)
    {
        NSDictionary *dictionary  = @{@"Cellname":titles[0],@"CellKey":titleskey[0],@"CellPic":titlePic[0],@"Celllist":groupdata};
        [alldata addObject:dictionary];
        nGroupCnt++;
    }
    
    //我的讨论组
    if(chatdata.count>0)
    {
        NSDictionary *dictionary  = @{@"Cellname":titles[1],@"CellKey":titleskey[1],@"CellPic":titlePic[1],@"Celllist":chatdata};
        [alldata addObject:dictionary];
        nGroupCnt++;
    }
    
    //最近联系人
    if(recentlydata.count>0)
    {
        NSDictionary *dictionary  = @{@"Cellname":titles[2],@"CellKey":titleskey[2],@"CellPic":titlePic[2],@"Celllist":recentlydata};
        [alldata addObject:dictionary];
    }
    
    //其他类
    for (int i = 3;i<titleskey.count;i++) {
        NSString *sqlWhere = [NSString stringWithFormat:@"where ref_id='%@' and operate='U' and type <> 'O'",titleskey[i]];
        NSMutableArray *arrList = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:sqlWhere]];
        if(arrList.count>0)
        {
            // 名称\关键字\图片\用户列表
            NSDictionary *dictionary  = @{@"Cellname":titles[i],@"CellKey":titleskey[i],@"CellPic":titlePic[i],@"Celllist":arrList};
            [alldata addObject:dictionary];
        }
    }
    [_tabContacts reloadData];
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return alldata.count;
}


-(UIView *)tableView:(UITableView*)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *viewtmp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 24)];
    viewtmp.backgroundColor = [UIColor whiteColor];
    
    BOOL bShowLabel = NO;
    if ((nGroupCnt==1 && section==0)||(nGroupCnt==2 && section==1)) {
        bShowLabel = YES;
            }
    
    UILabel *GrpLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 24)];
    
    if (bShowLabel) {
        GrpLable.text = @"  从校园联系人选择";
    }
    else
        GrpLable.text = @"";
    GrpLable.textAlignment = NSTextAlignmentLeft;
    GrpLable.font = [UIFont systemFontOfSize:12.0f];
    GrpLable.textColor = [UIColor colorWithRed:105.0f/255.0f green:105.0f/255.0f blue:105.0f/255.0f alpha:1.0f];
    GrpLable.backgroundColor = [UIColor colorWithRed:234.0f/255.0f green:234.0f/255.0f blue:238.0f/255.0f alpha:1.0f];
    [viewtmp addSubview:GrpLable];
    return viewtmp;
}

//设置view，将替代titleForHeaderInSection方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sIndex = [NSString stringWithFormat:@"%ld",(long)section];
    NSDictionary *dictionary = alldata[section];
    NSArray *arrlist = [dictionary objectForKey:@"Celllist"];
    if (arrlist.count>0) {
        UIView *viewtmp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
        viewtmp.backgroundColor = [UIColor whiteColor];
        int nY = 0;
        //第0项要加个标题
        if (section==0) {
            viewtmp.frame = CGRectMake(0, 0, 320, 74);
            UILabel *GrpLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 25)];
            if(nGroupCnt==0)
                GrpLable.text = @"  从校园联系人选择";
            else
                GrpLable.text = @"  从已加入群组选择";
            GrpLable.textAlignment = NSTextAlignmentLeft;
            GrpLable.font = [UIFont systemFontOfSize:12.0f];
            GrpLable.textColor = [UIColor colorWithRed:105.0f/255.0f green:105.0f/255.0f blue:105.0f/255.0f alpha:1.0f];
            GrpLable.backgroundColor = [UIColor colorWithRed:234.0f/255.0f green:234.0f/255.0f blue:238.0f/255.0f alpha:1.0f];
            [viewtmp addSubview:GrpLable];
            nY = 39;
            
        }
       else
           nY = 15;
           
        //如果是我的群组或者我的讨论组需要特殊处理
        if([[dictionary objectForKey:@"CellKey"] isEqualToString:@"Group"]|| [[dictionary objectForKey:@"CellKey"] isEqualToString:@"Chat"])
        {
            //图片为两层图片叠加
            UIImageView * grpCellImgBK = [[UIImageView alloc] initWithFrame:CGRectMake(8,nY, 20, 20)];
            grpCellImgBK.layer.masksToBounds = YES;
            grpCellImgBK.layer.cornerRadius = 10;
            if ([[dictionary objectForKey:@"CellKey"] isEqualToString:@"Group"]) {
                 grpCellImgBK.backgroundColor = [UIColor colorWithRed:254.0f/255.0f green:127.0f/255.0f blue:135.0f/255.0f alpha:1.0f];
            }
            if ([[dictionary objectForKey:@"CellKey"] isEqualToString:@"Chat"]) {
                 grpCellImgBK.backgroundColor = [UIColor colorWithRed:88.0f/255.0f green:188.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
            }
           
            [viewtmp addSubview:grpCellImgBK];
             UIImageView * grpCellImg = [[UIImageView alloc] initWithFrame:CGRectMake(3,5, 14, 9)];
            NSString *spic = [dictionary objectForKey:@"CellPic"];
            grpCellImg.image = [UIImage imageNamed:spic];
            [grpCellImgBK addSubview:grpCellImg];
            
        }
        else
        {
            //图片
            UIImageView * grpCellImg = [[UIImageView alloc] initWithFrame:CGRectMake(8,nY, 20, 20)];
            grpCellImg.layer.masksToBounds = YES;
            grpCellImg.layer.cornerRadius = 10;
            NSString *spic = [dictionary objectForKey:@"CellPic"];
            grpCellImg.image = [UIImage imageNamed:spic];
            [viewtmp addSubview:grpCellImg];
            
            //选择标识
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(tableView.frame.size.width-30, nY+5, 10, 10)];
            imageView.tag = 20000+section;
            
            //判断是不是选中状态
            if ([selectedArr containsObject:sIndex]) {
                imageView.image = [UIImage imageNamed:@"expanded.png"];
            }
            else
            {
                imageView.image = [UIImage imageNamed:@"unexpand.png"];
            }
            [viewtmp addSubview:imageView];
        }
        
        //标签
        UILabel *grpCellLable = [[UILabel alloc]initWithFrame:CGRectMake(33, nY, tableView.frame.size.width-30, 20)];
        grpCellLable.text = [NSString stringWithFormat:@"%@(%lu)",[dictionary objectForKey:@"Cellname"],(unsigned long)arrlist.count];
        grpCellLable.textAlignment = NSTextAlignmentLeft;
        grpCellLable.font = [UIFont systemFontOfSize:14.0f];
        [viewtmp addSubview:grpCellLable];
        
        //按钮
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, nY-15, 320, 40);
        button.tag = 100+section;
        [button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchUpInside];
        [viewtmp addSubview:button];
        return  viewtmp;
    }
    else
        return  nil;
}

-(void)doButton:(UIButton *)sender
{
    NSString *string = [NSString stringWithFormat:@"%ld",sender.tag-100];
    NSLog(@"点击索引：%@",string);
    //数组selectedArr里面存的数据和表头想对应，方便以后做比较
    if ([selectedArr containsObject:string])
    {
        [selectedArr removeObject:string]; //关闭
    }
    else
    {
        NSDictionary *dictonary = alldata[sender.tag-100];
        if([[dictonary objectForKey:@"CellKey"] isEqualToString:@"InstruStudent"]) //进入我辅导的学生页面
        {
            ShowStudentViewController *showstudent = [[ShowStudentViewController alloc] init];
            showstudent.sref_id =@"InstruStudent";
            showstudent.MyStudentType = SELECT_MYSTUDENT;
            showstudent.selectedContact = _selectedContact;
            showstudent.CreateType = _CreateType;
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:showstudent animated:NO];
        }
        else if([[dictonary objectForKey:@"CellKey"] isEqualToString:@"Group"] || [[dictonary objectForKey:@"CellKey"] isEqualToString:@"Chat"]) //群组或者讨论组
        {
            selectGroupViewController * gchat =[[selectGroupViewController alloc] initWithNibName:nil bundle:nil];
            gchat.GroupType =[dictonary objectForKey:@"CellKey"];
            gchat.selectedContact = _selectedContact;
            gchat.CreateType = _CreateType;
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:gchat animated:NO];
        }
        else{
            [selectedArr addObject:string]; //展开
        }
    }
   [_tabContacts reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if(section==0)
        return 74;
    else
        return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if ((nGroupCnt==1 && section==0)||(nGroupCnt==2 && section==1)) {
        return 24;
    }
    else
        return 12;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *sIndex = [NSString stringWithFormat:@"%ld",(long)section];
    if ([selectedArr containsObject:sIndex]) {   //展开
        
        UIImageView *imageV = (UIImageView *)[_tabContacts viewWithTag:20000+section];
        imageV.image = [UIImage imageNamed:@"expanded.png"];
        //我辅导的学生特别处理
        NSDictionary *dictionary = alldata[section];
        NSString *sTitleKey = [dictionary objectForKey:@"CellKey"];
        if([sTitleKey isEqualToString:@"InstruStudent"])
        {
            return 0;
        }
        else
        {
            NSArray *arrList = [dictionary objectForKey:@"Celllist"];
            return arrList.count;
        }
        
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"selectMemberTableViewCell";
    selectMemberTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    }
    NSDictionary *dictionary = alldata[indexPath.section];;
    NSArray *arrList = [dictionary objectForKey:@"Celllist"];
    Contact *contact =arrList[indexPath.row];
    
    [cell setContactSelected:[self containsContact:_selectedContact contact:contact]];
    [cell setSelectMemberTableViewCell:contact];
    
    return cell;
}

- (BOOL)containsContact:(NSMutableSet*) set contact:(Contact *)contact
{
    for (Contact * i   in  set)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            return YES;
        }
    }
    return NO;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dictionary = alldata[indexPath.section];;
    NSArray *arrList = [dictionary objectForKey:@"Celllist"];
    Contact *contact =arrList[indexPath.row];
    
    BOOL isFind = NO;
    for (Contact * i   in  _selectedContact)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            [_selectedContact removeObject:i];
            [_selectMemberList removeUnit:contact];
            isFind = YES;
            break;
        }
    }
    
    if (!isFind) {
        [_selectedContact addObject:contact];
        [_selectMemberList addNewUnit:contact];
    }
    
    
    NSArray *indexArray=[NSArray arrayWithObject:indexPath];
    [_tabContacts reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
    
}

-(void)touchBtnAtIndex:(NSInteger)index
{
    
    selectGroupViewController * gchat =[[selectGroupViewController alloc] initWithNibName:nil bundle:nil];
    
    if(index == 0)
    {//群列表
        gchat.GroupType =@"Group";
    }
    else if(index==1)
    {//讨论组列表
        gchat.GroupType =@"Chat";
    }    
    gchat.selectedContact = _selectedContact;
    gchat.CreateType = _CreateType;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:gchat animated:NO];
}


- (void) extendCellTouched:(UnitCell *)unitCell
{
    //点击选择好的成员后，需要清理数据
    Contact *contact =unitCell.contact;
    
    for (Contact * i   in  _selectedContact)
    {
        if ([i.mID isEqualToString:contact.mID]) {
            [_selectedContact removeObject:i];
            break;
        }
    }
}


- (void) unitDoneTouched:(id)sender
{
    if([_CreateType isEqualToString:CREATETYPE_CREATEGROUP])
    {
        NSLog(@"点击选择成员完成");
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[CreateGroupViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }
    }
    else if([_CreateType isEqualToString:CREATETYPE_ADDGROUP])
    {
        //添加群成员
        NSLog(@"添加群成员"); //GroupInfoViewController
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[GroupInfoViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }
        
    }
    else if([_CreateType isEqualToString:CREATETYPE_CREATECHAT])
    {
        //创建讨论组
        if(_selectedContact.count >200 || _selectedContact.count <2)
        {
            [self showAlerHUD:@"添加的成员人数不能小于2人和大于200人"];
            return;
        }
        
        /*"groupType":"1", --群组类型1 普通群 2 行政群 3 讨论组
         "userIds":"9004,9005,9006",--添加的用户列表，用逗号隔开 选填
         "groupName":"信网中心群",--群名称 选填
         "groupTags":"72,73,81",--群标签，多个值用逗号隔开 选填
         "toMountGroupId":"10000736",--挂靠的群组Id选填*/
        
        NSEnumerator *enumerator = [_selectedContact objectEnumerator];
        NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
        [ids insertString:[NSString stringWithFormat:@"%@,",DE.userId] atIndex:0];
        for (Contact *cid in enumerator) {
            [ids insertString:[NSString stringWithFormat:@"%@,",cid.mID] atIndex:0];
        }
        
        NSDictionary *dict  = @{@"groupType":@"3",
                                @"userIds":ids,
                                @"groupName":@"",
                                @"groupTags":@"",
                                @"toMountGroupId":@""};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"createGrp" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (success) {
                NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                
                [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                    
                    if(success){
                        @try {
                            [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                            [view show];
                        }
                        @catch (NSException *exception) {
                            [self showAlerHUD:@"创建讨论组失败！"];
                        }
                        
                    }else{
                        [self showAlerHUD:@"创建讨论组失败！"];
                        
                    }
                    
                }];
                
            }else{
                UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
                [view show];
            }
            
        }];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
   if (buttonIndex==0) {
       kAppDelegate.needRefrsh = YES;
        [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:NO];
    }
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
